/********************************************************************
 
 Copyright (C), 2012年 dhc. All rights reserved.
 
 Filename: 	    WebViewContrller.m 
 
 Author:        muzongcun
 
 Version:       1.0
 
 Description:   WebViewContrller
 
 History:
 
 muzongcun    2012/3/10     1.0     Create
 
 *********************************************************************/
//扩展名 	类型/子类型 	IIS 4.0 	IIS 5.0
//* 	application/octet-stream 	是 	是
//323 	text/h323 	否 	是
//acx 	application/internet-property-stream 	否 	是
//ai 	application/postscript 	是 	是
//aif 	audio/x-aiff 	是 	是
//aifc 	audio/x-aiff 	是 	是
//aiff 	audio/x-aiff 	是 	是
//asf 	video/x-ms-asf 	否 	是
//asr 	video/x-ms-asf 	否 	是
//asx 	video/x-ms-asf 	否 	是
//au 	audio/basic 	是 	是
//avi 	video/x-msvideo 	是 	是
//axs 	application/olescript 	否 	是
//bas 	text/plain 	是 	是
//bcpio 	application/x-bcpio 	是 	是
//bin 	application/octet-stream 	是 	是
//bmp 	image/bmp 	是 	是
//c 	text/plain 	是 	是
//cat 	application/vnd.ms-pkiseccat 	否 	是
//cdf 	application/x-cdf 	否 	是
//cer 	application/x-x509-ca-cert 	否 	是
//class 	application/octet-stream 	是 	是
//clp 	application/x-msclip 	是 	是
//cmx 	image/x-cmx 	是 	是
//cod 	image/cis-cod 	是 	是
//cpio 	application/x-cpio 	是 	是
//crd 	application/x-mscardfile 	是 	是
//crl 	application/pkix-crl 	否 	是
//crt 	application/x-x509-ca-cert 	否 	是
//csh 	application/x-csh 	是 	是
//css 	text/css 	否 	是
//dcr 	application/x-director 	是 	是
//der 	application/x-x509-ca-cert 	否 	是
//dir 	application/x-director 	是 	是
//dll 	application/x-msdownload 	否 	是
//dms 	application/octet-stream 	是 	是
//doc 	application/msword 	是 	是
//dot 	application/msword 	是 	是
//dvi 	application/x-dvi 	是 	是
//dxr 	application/x-director 	是 	是
//eps 	application/postscript 	是 	是
//etx 	text/x-setext 	是 	是
//evy 	application/envoy 	是 	是
//exe 	application/octet-stream 	是 	是
//fif 	application/fractals 	否 	是
//flr 	x-world/x-vrml 	是 	是
//gif 	image/gif 	是 	是
//gtar 	application/x-gtar 	是 	是
//gz 	application/x-gzip 	否 	是
//h 	text/plain 	是 	是
//hdf 	application/x-hdf 	是 	是
//hlp 	application/winhlp 	是 	是
//hqx 	application/mac-binhex40 	是 	是
//hta 	application/hta 	否 	是
//htc 	text/x-component 	否 	是
//htm 	text/html 	是 	是
//html 	text/html 	是 	是
//htt 	text/webviewhtml 	否 	是
//ico 	image/x-icon 	否 	是
//ief 	image/ief 	是 	是
//iii 	application/x-iphone 	否 	是
//ins 	application/x-internet-signup 	否 	是
//isp 	application/x-internet-signup 	否 	是
//jfif 	image/pipeg 	否 	是
//jpe 	image/jpeg 	是 	是
//jpeg 	image/jpeg 	是 	是
//jpg 	image/jpeg 	是 	是
//js 	application/x-javascript 	是 	是
//latex 	application/x-latex 	是 	是
//lha 	application/octet-stream 	是 	是
//lsf 	video/x-la-asf 	否 	是
//lsx 	video/x-la-asf 	否 	是
//lzh 	application/octet-stream 	是 	是
//m13 	application/x-msmediaview 	是 	是
//m14 	application/x-msmediaview 	是 	是
//m3u 	audio/x-mpegurl 	否 	是
//man 	application/x-troff-man 	是 	是
//mdb 	application/x-msaccess 	是 	是
//me 	application/x-troff-me 	是 	是
//mht 	message/rfc822 	否 	是
//mhtml 	message/rfc822 	否 	是
//mid 	audio/mid 	否 	是
//mny 	application/x-msmoney 	是 	是
//mov 	video/quicktime 	是 	是
//movie 	video/x-sgi-movie 	是 	是
//mp2 	video/mpeg 	是 	是
//mp3 	audio/mpeg 	否 	是
//mpa 	video/mpeg 	是 	是
//mpe 	video/mpeg 	是 	是
//mpeg 	video/mpeg 	是 	是
//mpg 	video/mpeg 	是 	是
//mpp 	application/vnd.ms-project 	是 	是
//mpv2 	video/mpeg 	是 	是
//ms 	application/x-troff-ms 	是 	是
//mvb 	application/x-msmediaview 	是 	是
//nws 	message/rfc822 	否 	是
//oda 	application/oda 	是 	是
//p10 	application/pkcs10 	否 	是
//p12 	application/x-pkcs12 	否 	是
//p7b 	application/x-pkcs7-certificates 	否 	是
//p7c 	application/x-pkcs7-mime 	否 	是
//p7m 	application/x-pkcs7-mime 	否 	是
//p7r 	application/x-pkcs7-certreqresp 	否 	是
//p7s 	application/x-pkcs7-signature 	否 	是
//pbm 	image/x-portable-bitmap 	是 	是
//pdf 	application/pdf 	是 	是
//pfx 	application/x-pkcs12 	否 	是
//pgm 	image/x-portable-graymap 	是 	是
//pko 	application/ynd.ms-pkipko 	否 	是
//pma 	application/x-perfmon 	是 	是
//pmc 	application/x-perfmon 	是 	是
//pml 	application/x-perfmon 	是 	是
//pmr 	application/x-perfmon 	是 	是
//pmw 	application/x-perfmon 	是 	是
//pnm 	image/x-portable-anymap 	是 	是
//pot, 	application/vnd.ms-powerpoint 	是 	是
//ppm 	image/x-portable-pixmap 	是 	是
//pps 	application/vnd.ms-powerpoint 	是 	是
//ppt 	application/vnd.ms-powerpoint 	是 	是
//prf 	application/pics-rules 	否 	是
//ps 	application/postscript 	是 	是
//pub 	application/x-mspublisher 	是 	是
//qt 	video/quicktime 	是 	是
//ra 	audio/x-pn-realaudio 	是 	是
//ram 	audio/x-pn-realaudio 	是 	是
//ras 	image/x-cmu-raster 	是 	是
//rgb 	image/x-rgb 	是 	是
//rmi 	audio/mid 	否 	是
//roff 	application/x-troff 	是 	是
//rtf 	application/rtf 	是 	是
//rtx 	text/richtext 	是 	是
//scd 	application/x-msschedule 	是 	是
//sct 	text/scriptlet 	否 	是
//setpay 	application/set-payment-initiation 	否 	是
//setreg 	application/set-registration-initiation 	否 	是
//sh 	application/x-sh 	是 	是
//shar 	application/x-shar 	是 	是
//sit 	application/x-stuffit 	否 	是
//snd 	audio/basic 	是 	是
//spc 	application/x-pkcs7-certificates 	否 	是
//spl 	application/futuresplash 	否 	是
//src 	application/x-wais-source 	是 	是
//sst 	application/vnd.ms-pkicertstore 	否 	是
//stl 	application/vnd.ms-pkistl 	否 	是
//stm 	text/html 	是 	是
//sv4cpio 	application/x-sv4cpio 	是 	是
//sv4crc 	application/x-sv4crc 	是 	是
//t 	application/x-troff 	是 	是
//tar 	application/x-tar 	是 	是
//tcl 	application/x-tcl 	是 	是
//tex 	application/x-tex 	是 	是
//texi 	application/x-texinfo 	是 	是
//texinfo 	application/x-texinfo 	是 	是
//tgz 	application/x-compressed 	否 	是
//tif 	image/tiff 	是 	是
//tiff 	image/tiff 	是 	是
//tr 	application/x-troff 	是 	是
//trm 	application/x-msterminal 	是 	是
//tsv 	text/tab-separated-values 	是 	是
//txt 	text/plain 	是 	是
//uls 	text/iuls 	否 	是
//ustar 	application/x-ustar 	是 	是
//vcf 	text/x-vcard 	否 	是
//vrml 	x-world/x-vrml 	是 	是
//wav 	audio/x-wav 	是 	是
//wcm 	application/vnd.ms-works 	是 	是
//wdb 	application/vnd.ms-works 	是 	是
//wks 	application/vnd.ms-works 	是 	是
//wmf 	application/x-msmetafile 	是 	是
//wps 	application/vnd.ms-works 	是 	是
//wri 	application/x-mswrite 	是 	是
//wrl 	x-world/x-vrml 	是 	是
//wrz 	x-world/x-vrml 	是 	是
//xaf 	x-world/x-vrml 	是 	是
//xbm 	image/x-xbitmap 	是 	是
//xla 	application/vnd.ms-excel 	是 	是
//xlc 	application/vnd.ms-excel 	是 	是
//xlm 	application/vnd.ms-excel 	是 	是
//xls 	application/vnd.ms-excel 	是 	是
//xlt 	application/vnd.ms-excel 	是 	是
//xlw 	application/vnd.ms-excel 	是 	是
//xof 	x-world/x-vrml 	是 	是
//xpm 	image/x-xpixmap 	是 	是
//xwd 	image/x-xwindowdump 	是 	是
//z 	application/x-compress 	否 	是
//zip 	application/zip 	是 	是
#import "WebViewContrller.h"
#import "HttpServerURL.h"
#import "ASIHTTPRequest.h"
#import "Type.h"

#define BARBUTTON(TITLE, SELECTOR) 	[[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR]//UIBarButtonItem
#define TOOLBAR 102

@implementation WebViewContrller
@synthesize URLPage;
@synthesize m_navBar;
@synthesize m_title; 
@synthesize m_fileID;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad 
{
    [super viewDidLoad];
	[self initData];
    
    //最上面的bar
    m_navBar=[[UINavigationBar alloc]init];
    m_navBar.frame = CGRectMake(0, 0, 320, 44);
    UIImage* imageBar = [UIImage imageNamed:PIC_MAIL_TOP_BAR];

    NSString* devVersion = [[UIDevice currentDevice] systemVersion];
    if ([devVersion compare:@"4.3.3"] == 0)
    {
        [m_navBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)];
        [m_navBar setTintColor:NAVIGATION_BAR_COLOR];
    }else
    {
        [m_navBar setBackgroundImage:imageBar forBarMetrics:UIBarMetricsDefault];
    }
    //返回按钮
    UIButton* barRetBut = [[UIButton alloc] initWithFrame:CGRectMake(5.0, 10.0, 50.0, 25.0)];
    [barRetBut setTitle:@" 返回" forState:UIControlStateNormal];
    UIFont *font              = [UIFont systemFontOfSize:14];
    barRetBut.titleLabel.font = font;
    UIImage *retButImageNormal = [UIImage imageNamed:PIC_MAIL_SWITCH_SELF_NORMAL];
    [barRetBut setBackgroundImage:retButImageNormal forState:UIControlStateNormal];
    //[retButImageNormal release];
    UIImage *retButImagePressed = [UIImage imageNamed:PIC_MAIL_SWITCH_SELF_PRESS];
    [barRetBut setBackgroundImage:retButImagePressed forState:UIControlStateHighlighted];
    //[retButImagePressed release];
    [barRetBut addTarget:self action:@selector(onNavigation) forControlEvents:UIControlEventTouchUpInside];
    
    //邮箱title
    m_barTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(100.0, 5.0, 220.0, 32.0)];
    [m_barTitleLabel setBackgroundColor:[UIColor  clearColor]];
    //[m_barTitleLabel setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
    m_barTitleLabel.textColor = [UIColor whiteColor];
    m_barTitleLabel.text = m_title;
    [m_barTitleLabel setContentMode:UIViewContentModeScaleToFill];
    //添加button到topbar上
    [m_navBar addSubview:barRetBut];
    [m_navBar addSubview:m_barTitleLabel];
    
	NSUserDefaults *UserDefaults = [NSUserDefaults standardUserDefaults];
	URLPage = [UserDefaults integerForKey:@"PageKey"];
	
	WebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 44, 320, 400)];
	[WebView setUserInteractionEnabled:NO];
	[WebView setBackgroundColor:[UIColor clearColor]];
	[WebView setDelegate:self];
	[WebView setOpaque:NO];
    NSString* attachFileUrl =  [HttpServerURL GetInstance].serverFileUrl;
    NSString* strURL = [NSString stringWithFormat:@"%@%@",attachFileUrl,m_fileID];
    NSURL *url   =   [NSURL URLWithString:strURL]; 
    ASIHTTPRequest *request = [[[ASIHTTPRequest  alloc] initWithURL:url] autorelease]; 
    [request setValidatesSecureCertificate:NO];
    request.shouldAttemptPersistentConnection = NO;
    [request startSynchronous]; 
    NSError *error = [request error]; 
    if(!error)
    { 
        NSData* responseData = [request responseData];
        NSString *ext = [[m_title pathExtension] lowercaseString];
        NSString *mimeType;
        if([ext isEqualToString:@"doc"])
        {
            mimeType = @"application/msword";
        }
        else if([ext isEqualToString:@"ppt"])
        {
            mimeType = @"application/vnd.ms-powerpoint";
        }
        else if([ext isEqualToString:@"xls"])
        {
            mimeType = @"application/vnd.ms-excel";
        }
        else if([ext isEqualToString:@"wma"])
        {
            mimeType = @"audio/x-ms-wma";
        }
        else if([ext isEqualToString:@"jpg"] || [ext isEqualToString:@"jpeg"])
        {
            mimeType = @"image/jpeg";
        }
        else if([ext isEqualToString:@"tif"]||[ext isEqualToString:@"tiff"])
        {
            mimeType = @"image/tiff";
        }
        else if([ext isEqualToString:@"htm"]||[ext isEqualToString:@"html"])
        {
            mimeType = @"text/html";
        }
        else if([ext isEqualToString:@"mov"])
        {
            mimeType = @"video/quicktime";
        }
        else if([ext isEqualToString:@"mp4"])
        {
            mimeType = @"video/mp4";
        }
        else if([ext isEqualToString:@"txt"])
        {
            mimeType = @"text/plain";
        }
        else if([ext isEqualToString:@"7z"])
        {
            mimeType = @"application/x-compress";
        }
        else if([ext isEqualToString:@"zip"])
        {
            mimeType = @"application/zip";
        }
        
        else if([ext isEqualToString:@"mid"])
        {
            mimeType = @"audio/mid";
        }
        else if([ext isEqualToString:@"mp3"])
        {
            mimeType = @"audio/mpeg";
        }
        else if([ext isEqualToString:@"mpeg"])
        {
            mimeType = @"audio/mpeg";
        }              
        else
        {
            mimeType = [NSString stringWithFormat:@"application/%@", ext];    //pdf
        }
        
        if(responseData) 
        {  
            [WebView loadData:responseData MIMEType:mimeType textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:strURL]];        
        }  
    } 
 
	
	UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
	[view setTag:103];
	activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
	[activityIndicator setCenter:view.center];
	[activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
	[view setBackgroundColor:[UIColor blackColor]];
	[view setAlpha:0.8];
	[self.view addSubview:view];
	[view addSubview:activityIndicator];
	[view release];
	[self.view addSubview:WebView];
	[WebView release];
	
	
	//Creat ToolBar
	UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 420, 320, 40)];
	[toolbar setTag:TOOLBAR];
	toolbar.barStyle = self.navigationController.navigationBar.barStyle;
	UIBarButtonItem *PreBtn = BARBUTTON(@"Pre", @selector(Pre:));
	

	//建立中间两个空按钮
	UIBarButtonItem *Item1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
																		   target:nil
																		   action:nil];
	
	UIBarButtonItem *Item2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
																		   target:nil
																		   action:nil];
	
	UIBarButtonItem *NextBtn = BARBUTTON(@"Next", @selector(NextBtn:));
	NSArray *items = [NSArray arrayWithObjects: PreBtn, Item1, Item2, NextBtn, nil];
	toolbar.hidden = YES;
	[toolbar setItems:items animated:NO];
	[self.view addSubview:toolbar];
    [self.navigationController.view addSubview:m_navBar];
    
     self.view.backgroundColor = BACKGROUND_COLOR;
    
	[PreBtn release];
	[Item1 release];
	[Item2 release];
	[NextBtn release];
	[toolbar release];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
	[activityIndicator stopAnimating];	
	UIView *view = (UIView *)[self.view viewWithTag:103];
	[view removeFromSuperview];
}

- (void)webViewDidStartLoad:(UIWebView *)webView {     
	[activityIndicator startAnimating];	     
}


-(void)initData
{
	URLPage = 0;
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType 
{
	return YES;
}


-(void)Pre:(id)sender
{
	[WebView goBack];
}


-(void)NextBtn:(id)sender
{
	[WebView goForward];
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
	UIToolbar *toolbar = (UIToolbar *)[self.view viewWithTag:TOOLBAR];
	UITouch *touch = [[event allTouches] anyObject];
	if (touch.tapCount == 1) {
		if (isHidden == NO) 
		{
			CGContextRef context = UIGraphicsGetCurrentContext();
			[UIView beginAnimations:nil context:context];
			[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
			[UIView setAnimationDuration:0.3];
			[WebView setUserInteractionEnabled:NO];
			//self.navigationController.navigationBarHidden = YES;
			toolbar.hidden = NO;
			[UIView commitAnimations];
			isHidden = YES;
		}else 
		{
			CGContextRef context = UIGraphicsGetCurrentContext();
			[UIView beginAnimations:nil context:context];
			[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
			[UIView setAnimationDuration:0.3];
			self.navigationController.navigationBarHidden = YES;
			toolbar.hidden = YES;
			[WebView setUserInteractionEnabled:YES];
			[UIView commitAnimations];
			isHidden = NO;			
		}
		
	}
 
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning 
{
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload 
{
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc 
{
    [super dealloc];
}

-(void)onNavigation
{
    self.m_navBar.hidden = YES;
    [self.navigationController popViewControllerAnimated :NO];
}
@end
